package com.jorado.core.scheduler;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class TaskPool {

    private static final int INIT_SIZE = 64;

    private static Map<Integer, TaskInfo> TASK_HOLDER = new ConcurrentHashMap<>(INIT_SIZE, 0.5F);

    public static boolean exists(int taskId) {
        return TASK_HOLDER.containsKey(taskId);
    }

    public static synchronized void add(TaskInfo taskInfo) {
        TASK_HOLDER.put(taskInfo.taskId, taskInfo);

    }

    public static synchronized void remove(int taskId) {
        TASK_HOLDER.remove(taskId);
    }

    public static synchronized void clear() {
        TASK_HOLDER.clear();
    }

    public static synchronized List<TaskInfo> getWaitRunTasks() {
        List<TaskInfo> tasks = new ArrayList<>();
        Calendar now = Calendar.getInstance();
        for (int tid : TASK_HOLDER.keySet()) {
            TaskInfo task = TASK_HOLDER.get(tid);
            int i = now.compareTo(task.nextRunTime);
            if (i >= 0) {
                tasks.add(task);
                task.nextRunTime.add(Calendar.YEAR, 30);
            }
        }
        return tasks;
    }

    public static void main(String[] args) {
        Calendar next = Calendar.getInstance();
        next.add(Calendar.MINUTE, 2);
        TaskPool.add(new TaskInfo(1, next));
        List<TaskInfo> _tasks = getWaitRunTasks();
        System.out.println(_tasks);
    }
}
